package com.tang.gateway.filter;

import com.tang.common.utils.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1. 获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 判断当前的请求是否为登录 如果是 直接放行

        if (request.getURI().getPath().contains("/login")||
                request.getURI().getPath().contains("/adminLogin")
                ||request.getURI().getPath().contains("/captcha")
                ||request.getURI().getPath().contains("/register")
                ||request.getURI().getPath().contains("/forgetPwd")
                ||request.getURI().getPath().contains("/")
                || request.getURI().getPath().contains("/upload")){
//            System.out.println("无需token直接放行"+request.getURI().getPath());

            //放行
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                //只允许通过网关访问
                httpHeaders.add("systemFrom", "gateway");
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
            return chain.filter(exchange);
        }
        //3. 获取当前用户的请求头jwt信息
        HttpHeaders headers = request.getHeaders();
        String jwtToken = headers.getFirst("TOKEN");

        //4. 判断当前令牌是否存在
        if (StringUtils.isEmpty(jwtToken)){
            //如果不存在 向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断jwt和redis中令牌是否一致，不一致则提示已经在其他地方登陆，并重新跳回登陆界面

        try {
            //5. 如果令牌存在 解析jwt令牌 判断该令牌是否合法 如果不合法 则向客户端返回错误提示信息
            int result = JwtUtil.verifyToken(jwtToken);
            if (result == -1 || result == 0){
                //5.1 合法 则向header中设置username
                String username = JwtUtil.get(jwtToken, "username");
                String role = JwtUtil.get(jwtToken, "role");
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("username",role);
                    httpHeaders.add("role",username);
                    //只允许通过网关访问
                    httpHeaders.add("systemFrom", "gateway");
                    httpHeaders.add("TOKEN", jwtToken);
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
//                System.out.println("需要token"+request.getURI().getPath());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6. 放行
        return chain.filter(exchange);
    }

    /**
     * 优先级设置
     * 值越小 优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        //只允许通过网关访问
        return 0;
    }
}

